package com.lwc.backendsinglestructure.interceptor;

import com.lwc.backendsinglestructure.common.utils.TraceIdUtil;
import com.lwc.backendsinglestructure.constants.LogConstant;
import com.lwc.backendsinglestructure.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.Map;

/**
 * 登录拦截器
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1. 如果前端没有传递 TraceId， 服务端可以自己生成
        String trace_id = request.getHeader(LogConstant.TRACE_ID);
        if(trace_id == null){
            trace_id = TraceIdUtil.getTraceId();
        }
        MDC.put(LogConstant.TRACE_ID, trace_id);

        HashMap<String, Object> hashMap = new HashMap<>();
        String ip = getIpAddr(request);
        String browserInfo = getBrowserInfo();
        hashMap.put("ip", ip);
        hashMap.put("browser", browserInfo);
        hashMap.put(LogConstant.TRACE_ID, trace_id);

        ThreadLocalUtil.set(hashMap);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        ThreadLocalUtil.remove();
        MDC.clear();
    }

    /**
     * 获取真实IP
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if ("0:0:0:0:0:0:0:1".equals(ip)) {
            ip = "127.0.0.1";
        }
        if (ip.split(",").length > 1) {
            ip = ip.split(",")[0];
        }
        return ip;
    }

    /**
     * 获取浏览器信息
     * @return 浏览器信息
     */
    public static String getBrowserInfo() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            return null;
        }

        HttpServletRequest request = attributes.getRequest();
        return request.getHeader("User-Agent");
    }
}
